package com.alinesno.cloud.base.boot.web.module.settings;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alinesno.cloud.base.boot.entity.ManagerSourceGenerateEntity;
import com.alinesno.cloud.base.boot.service.IManagerSourceGenerateService;
import com.alinesno.cloud.common.core.constants.SpringInstanceScope;
import com.alinesno.cloud.common.core.page.DatatablesPageBean;
import com.alinesno.cloud.common.core.response.ResponseBean;
import com.alinesno.cloud.common.core.response.ResponseGenerator;
import com.alinesno.cloud.common.web.base.advice.TranslateCode;
import com.alinesno.cloud.common.web.base.controller.FeignMethodController;

/**
 * 代码生成器
 * 
 * @author LuoAnDong
 * @since 2019年4月8日 下午10:29:02
 */
@Controller
@Scope(SpringInstanceScope.PROTOTYPE)
@RequestMapping("boot/platform/source")
public class SourceGenerateController
		extends FeignMethodController<ManagerSourceGenerateEntity, IManagerSourceGenerateService> {

	private static final Logger log = LoggerFactory.getLogger(SourceGenerateController.class);

	@Reference
	private IManagerSourceGenerateService managerSourceGenerateService ; 

	@Value("${alinesno.compoment.generator.path}")
	private String generatorPath;

	@TranslateCode(value = "[{hasStatus:has_status}]")
	@ResponseBody
	@RequestMapping("/datatables")
	public DatatablesPageBean datatables(HttpServletRequest request, Model model, DatatablesPageBean page) {
		log.debug("page = {}", ToStringBuilder.reflectionToString(page));
		return this.toPage(model, managerSourceGenerateService, page);
	}

	/**
	 * 保存新对象
	 * 
	 * @param model
	 * @param managerCodeDto
	 * @return
	 * @throws IOException
	 */
//	@AccountRecord(type = RecordType.OPERATE_SAVE)
//	@ResponseBody
//	@PostMapping("/generator")
//	public ResponseBean generator(Model model, HttpServletRequest request, ManagerSourceGenerateEntity dto)
//			throws IOException {
//		log.debug("generatorPath:{} , dto:{}", generatorPath, ToStringBuilder.reflectionToString(dto));
//
//		Date date = new Date();
//		
//		//转义DBURL
//		dto.setDbUrl(HtmlUtil.unescape(dto.getDbUrl()));
//
//		String downPath = generatorPath + "/" + new SimpleDateFormat("yyyy/MM").format(date) + "/" + dto.getFeignServerPath();
//		File f = new File(downPath);
//
//		log.debug("downPath:{}" , downPath);
//		
//		if (f.exists()) {
//			FileUtils.forceDelete(f);
//		}
//		FileUtils.forceMkdir(f);
//		
//		Generator g = new GeneratorSourceTool(dto, downPath);
//		g.generator(null);
//		String targetPath = downPath + "-" + System.currentTimeMillis() + ".zip";
//		ZipUtils.toZip(downPath, targetPath, true);
//
//		dto.setFieldProp(targetPath);
//		dto = managerSourceGenerateService.save(dto);
//		return ResponseGenerator.ok(dto.getId());
//	}

	/**
	 * 下载文件 (分布式部署待优化)
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/downloadCode")
	public ResponseEntity<byte[]> download(HttpServletRequest request, String id) throws IOException {
		
//		Optional<ManagerSourceGenerateEntity> optional = managerSourceGenerateService.findById(id) ; 
//		File file = new File(optional.get().getFieldProp());
//		InputStream is = new FileInputStream(file);
//		body = new byte[is.available()];
//		is.read(body);
		
		byte[] body = managerSourceGenerateService.generatorCode(id) ;
		
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition", "attchement;filename=" + System.currentTimeMillis() + ".zip" );
		
		HttpStatus statusCode = HttpStatus.OK;
		ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
		return entity;
	}

	@RequestMapping("/uploadCode")
	public ResponseBean upload(HttpServletRequest request, String id) throws IOException {
		
//		Optional<ManagerSourceGenerateEntity> optional = this.getFeign().findById(id) ; 
//		File file = new File("/tmp/"+System.currentTimeMillis());
//		if(!file.exists()) {
//			file.mkdir();
//		}
//		boolean cloneResult = GitTools.cloneGit(optional.get().getGitRepositoryUrl(), file);
//		if(!cloneResult) {
//			return ResponseGenerator.genFailMessage("远程仓库克隆失败！");
//		}
//		boolean commitResult = GitTools.commitAndPush(file, optional.get().getGitUserName(), optional.get().getGitPassword(), "提交项目代码到远程仓库");
//		if(!commitResult) {
//			return ResponseGenerator.genFailMessage("远程仓库提交失败！");
//		}
		
		managerSourceGenerateService.git(id) ; 
		return ResponseGenerator.ok(id);
	}

	@Override
	public IManagerSourceGenerateService getFeign() {
		return managerSourceGenerateService;
	}

	/**
	 * 进入设置界面 
	 */
	@RequestMapping("/settings")
	public void settings() {
		log.debug("开发平台配置.");
	}

}
